package com.lw.sbdemo2.common.utils;

import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

import javax.xml.stream.XMLStreamReader;

/**
 * <p>标题: XML错误处理Handler</p>
 * <p>描述: XML格式错误不会抛异常，而是在这个类捕获，错误内容定位到具体元素</p>
 * <p>版权: Copyright (c) 2016</p>
 * <p>公司: 智业软件</p>
 *
 * @version: 1.0
 * @author: WuJianX
 * @date: 2017/3/7
 */
public class XmlErrorHandler implements ErrorHandler {
    private String errorText;
    private String errorCode;
    private XMLStreamReader reader;

    public XmlErrorHandler(XMLStreamReader reader) {
        this.reader = reader;
    }

    @Override
    public void warning(SAXParseException e) throws SAXException {
        fatalError(e);
    }

    @Override
    public void error(SAXParseException e) throws SAXException {
        fatalError(e);
    }

    @Override
    public void fatalError(SAXParseException e) throws SAXException {

        String msg = e.getMessage();

        try {
            String element = reader.getLocalName();
            this.errorText = "校验失败:发现以<" + element + ">元素开头的无效内容";
        } catch (Exception e1) {
            this.errorText = msg;
        }
    }

    public String getErrorText() {
        return errorText;
    }

    public void setErrorText(String errorText) {
        this.errorText = errorText;
    }

    public String getErrorCode() {
        return errorCode;
    }

    public void setErrorCode(String errorCode) {
        this.errorCode = errorCode;
    }

    public XMLStreamReader getReader() {
        return reader;
    }

    public void setReader(XMLStreamReader reader) {
        this.reader = reader;
    }

}
